package com.romanito.timer;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

public class TimerRing extends Activity implements OnClickListener {

	private static final String TAG = "Timer"; 
	
	Vibrator mVibrator;
	
	private LinearLayout ll_times_up;
	private MediaPlayer media_player;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
        setVolumeControlStream(AudioManager.STREAM_ALARM);
		setContentView(R.layout.ring);
		
		ll_times_up = (LinearLayout) findViewById(R.id.ll_times_up);
		ll_times_up.setOnClickListener(this);
		
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
	    SharedPreferences.Editor pref_edit = preferences.edit();
	    pref_edit.putLong("start_time", 0L);
	    pref_edit.commit();
		
		Bundle extras = getIntent().getExtras();
		if (extras.containsKey("NotifId")) {
			NotificationManager notif_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			notif_manager.cancel(extras.getInt("NotifId"));
		}
		
        try {
        	media_player = new MediaPlayer();
            AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.alarm_beep);

            media_player.setDataSource(afd.getFileDescriptor(),
                             afd.getStartOffset(),
                             afd.getLength());

            if (media_player != null) {
            	media_player.setAudioStreamType(AudioManager.STREAM_ALARM);
            	media_player.setLooping(true);
            	media_player.prepare();
    			media_player.start();
            }
        } catch (Exception ex) {
            Log.w(TAG, "Couldn't create alarm sound", ex);
        }		
        
        if (preferences.getBoolean("vibrate", false)) {
        	mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        	mVibrator.vibrate(new long[] { 500, 500 }, 0);
        }
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_times_up:
			finish();
			break;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (media_player != null) 
			media_player.stop();
		
		if (mVibrator != null)
			mVibrator.cancel();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (media_player != null) {
			media_player.release();
			media_player = null;
		}
	}



}
